package com.squirrel.michale;

/**
 * @author guanhao 观浩
 * @version 1.0.0.0
 * @createTime 2023/3/9 8:48 PM
 * @company Michale Squirrel
 * @link
 * @description
 */
public class LeetCode2055 {

    public int[] platesBetweenCandles(String s, int[][] queries) {
        char[] chars = s.toCharArray();
        int n = chars.length;
        int[] preSum = new int[n];
        int[] previousCandle = new int[n];
        int[] nextCandle = new int[n];
        int candlesCount = 0;
        int previous = -1;
        for (int i = 0; i < n; i++) {
            candlesCount += chars[i] == '*' ? 1 : 0;
            preSum[i] = candlesCount;
            if (chars[i] == '|') {
                previous = i;
            }
            previousCandle[i] = previous;
        }


        int next = n;
        for (int i = n-1; i >=0 ; i--) {
            if (chars[i] == '|') {
                next = i;
            }
            nextCandle[i] = next;
        }

        int m = queries.length;
        int[] result = new int[m];
        for (int i = 0; i < m; i++) {
            int[] query = queries[i];
            int a = query[0];
            int b = query[1];
            int x = nextCandle[a];
            int y = previousCandle[b];
            if (x >= a && y <= b && x <= y) {
                result[i] = preSum[y] - preSum[x];
            }else{
                result[i] = 0;
            }
        }
        return result;
    }
}
